package com.hydl.power.controller;

import com.github.pagehelper.PageInfo;
import com.hydl.power.aop.annotation.LogAnnotation;
import com.hydl.power.pojo.*;
import com.hydl.power.service.DeviceService;
import com.hydl.power.service.MaintainerService;
import com.hydl.power.service.OrderDeliveryService;
import com.hydl.power.service.WorkOrderService;
import com.hydl.power.utils.IdUtil;
import com.hydl.power.utils.Resp;
import io.micrometer.core.instrument.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author wxb
 * @date 2020/3/31 15:14
 */
@Api(value = "OrderDeliveryController",tags = "工单派送/工单查询")
@RequestMapping("/orderDelivery")
@RestController
@CrossOrigin
public class OrderDeliveryController {

    @Autowired
    private OrderDeliveryService orderDeliveryService;
    @Autowired
    private MaintainerService maintainerService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private WorkOrderService workOrderService;


    // @LogAnnotation(module = "工单派送/工单查询",description = "查询工单派送列表")
    @ApiOperation("查询工单派送列表")
    @PostMapping("/getAllOrderDeliveryByList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "pageNum", value = "页数", dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "条数",dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "beginTime", value = "开始故障时间",dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "endTime", value = "结束故障时间",dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "orderTypes", value = "工单类型 1告警工单 2巡查工单 3 检修 4实验", dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "rank", value = "处理级别  1 一般 2紧急 3严重", dataType = "Integer"),
    })
    public Resp<PageInfo<WorkOrder>> getAllOrderDeliveryByList(Integer pageNum, Integer pageSize, String beginTime, String endTime, Integer orderTypes, Integer rank) {
        PageInfo<WorkOrder> list = workOrderService.getAllWorkOrderByList(pageNum, pageSize,  IdUtil.str2Long(beginTime), IdUtil.str2Long(endTime), orderTypes, rank, 1);
        return Resp.success(list);
    }


    //  @LogAnnotation(module = "工单派送/工单查询",description = "查询工单查询列表")
    @ApiOperation("查询工单查询列表")
    @PostMapping("/getOrderDelivery")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "pageNum", value = "页数", dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "条数",dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "begin", value = "开始故障时间",dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "end", value = "结束故障时间",dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "orderStatus", value = "工单状态  1待派送 2待处理(派送工单) 3处理中 4 忽略工单(以忽略) 5 以结束",dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "maintainerId", value = "运维员Id", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "areaId", value = "区域id",dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "projectId", value = "单位id",dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "roomId", value = "配电房id",dataType = "String"),
    })
    public Resp<PageInfo<WorkOrder>> getOrderDelivery(Integer pageNum,Integer pageSize,String begin,String end,Integer orderStatus,Integer maintainerId,String areaId,String projectId,String roomId){
        PageInfo<WorkOrder> orderDeliveryPageInfo = workOrderService.getAllWorkOrderTwo(pageNum, pageSize,begin,end, orderStatus,maintainerId, areaId, projectId, roomId);
        return Resp.success(orderDeliveryPageInfo);
    }



    //  @LogAnnotation(module = "工单派送/工单查询",description = "工单查询导出")
    @ApiOperation("工单查询导出")
    @PostMapping("/exportOrderJY")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "pageNum", value = "页数", dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "条数",dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "begin", value = "开始故障时间",dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "end", value = "结束故障时间", dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "orderStatus", value = "工单状态  1待派送 2待处理(派送工单) 3处理中 4 忽略工单(以忽略) 5 以结束",dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "maintainerId", value = "运维员名字", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "areaId", value = "区域id",dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "projectId", value = "单位id",dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "roomId", value = "配电房id",dataType = "String"),
    })
    public void exportOrderJY(HttpServletResponse response,Integer pageNum,Integer pageSize,String begin,String end,Integer orderStatus,Integer maintainerId,String areaId,String projectId,String roomId) {
        Long beginTime = null;
        Long endTime = null;
        if (StringUtils.isNotEmpty(begin)) {
            beginTime = IdUtil.str2Long(begin);
        }
        if (StringUtils.isNotEmpty(end)) {
            endTime = IdUtil.str2Long(end);
        }
        PageInfo<OrderDelivery> orderDeliveryPageInfo = orderDeliveryService.getOrderDelivery(pageNum, pageSize, beginTime, endTime, orderStatus,maintainerId, areaId, projectId, roomId);
        //PageInfo<OrderDelivery> orderDeliveryPageInfo = orderDeliveryService.getOrderDelivery(pageNum, pageSize, IdUtil.str2Long(begin), IdUtil.str2Long(end), orderStatus,maintainerName, areaId, projectId, roomId);
        List<OrderDelivery> list = orderDeliveryPageInfo.getList();
        String fileName = new SimpleDateFormat("yyyy-MM-dd ").format(new Date()) + "工单查询表";
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        HSSFSheet sheet = hssfWorkbook.createSheet();
        HSSFRow title = sheet.createRow(0);
        title.createCell((short) 0).setCellValue(new HSSFRichTextString("派单号"));
        title.createCell((short) 1).setCellValue(new HSSFRichTextString("工单状态"));
        title.createCell((short) 2).setCellValue(new HSSFRichTextString("故障时间"));
        title.createCell((short) 3).setCellValue(new HSSFRichTextString("故障类型"));
        title.createCell((short) 4).setCellValue(new HSSFRichTextString("故障内容"));
        title.createCell((short) 5).setCellValue(new HSSFRichTextString("派单时间"));
        title.createCell((short) 6).setCellValue(new HSSFRichTextString("处理人员"));
        title.createCell((short) 7).setCellValue(new HSSFRichTextString("处理开始时间"));
        title.createCell((short) 8).setCellValue(new HSSFRichTextString("处理结束时间"));
        title.createCell((short) 9).setCellValue(new HSSFRichTextString("处理级别"));

        for (int i = 1; i <= list.size(); i++) {
            OrderDelivery orderDelivery = list.get(i - 1);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time1 = sdf.format((orderDelivery.getFaultTime()));
            String time2 = sdf.format((orderDelivery.getOrderDeliveryTime()));
            String time3 = sdf.format((orderDelivery.getDealBeginTime()));
            String time4 = sdf.format((orderDelivery.getDealEndTime()));
            //状态
            String s1 = null;
            if (1 == orderDelivery.getOrderStatus()) {
                s1 = "待派送";
            } else if (2 == orderDelivery.getOrderStatus()) {
                s1 = "待处理";
            } else if (3 == orderDelivery.getOrderStatus()) {
                s1 = "处理中";
            } else if (4 == orderDelivery.getOrderStatus()) {
                s1 = "忽略工单";
            } else if (5 == orderDelivery.getOrderStatus()) {
                s1 = "已结束";
            }
            String s2 = null;
            if (1 == orderDelivery.getRank()) {
                s2 = "一般";
            } else if (2 == orderDelivery.getRank()) {
                s2 = "紧急";
            } else if (3 == orderDelivery.getRank()) {
                s2 = "严重";
            }
            String s3 = null;
            if (1 == orderDelivery.getFaultTypes()) {
                s3 = "越限告警";
            }
            HSSFRow title1 = sheet.createRow(i);
            title1.createCell((short) 0).setCellValue(new HSSFRichTextString(orderDelivery.getOrderDeliveryId()));
            title1.createCell((short) 1).setCellValue(new HSSFRichTextString(s1));
            title1.createCell((short) 2).setCellValue(new HSSFRichTextString(time1));
            title1.createCell((short) 3).setCellValue(new HSSFRichTextString(s3));
            title1.createCell((short) 4).setCellValue(new HSSFRichTextString(orderDelivery.getFault()));
            title1.createCell((short) 5).setCellValue(new HSSFRichTextString(time2));
            title1.createCell((short) 6).setCellValue(new HSSFRichTextString(orderDelivery.getMaintainerName()));
            title1.createCell((short) 7).setCellValue(new HSSFRichTextString(time3));
            title1.createCell((short) 8).setCellValue(new HSSFRichTextString(time4));
            title1.createCell((short) 9).setCellValue(new HSSFRichTextString(s2));
        }

        try {
            OutputStream outputStream = response.getOutputStream();
            response.reset();
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes("utf-8"), "iso-8859-1"));
            response.setContentType("application/msexcel");
            hssfWorkbook.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @LogAnnotation(module = "工单派送/工单查询",description = "忽略工单")
    @PostMapping("updateOrderStatusById")
    @ApiOperation(value = "忽略工单", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "id", dataType = "Integer"),
    })
    public Resp updateOrderStatusById(Integer id) {
        int i = workOrderService.updateOrderStatusById(id,4);
        if (i == 1){
            return Resp.success("忽略工单成功");
        }
        return Resp.success("忽略工单失败");
    }


    //  @LogAnnotation(module = "工单派送/工单查询",description = "根据ID获取工单")
    @ApiOperation(value="根据ID获取工单")
    @PostMapping("/getOrderDeliveryById")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "用户id", dataType = "Integer"),
    })
    public Resp getOrderDeliveryById(Integer id){
        return Resp.success(workOrderService.getById(id));
    }


    // @LogAnnotation(module = "工单派送/工单查询",description = "运维人员实时定位")
    @ApiOperation("获取运维人员列表")
    @GetMapping("/getAllMaintainer")
    public Resp<List<Maintainer>> getAllUser() {
        return Resp.success(maintainerService.getAll());
    }


    @LogAnnotation(module = "工单派送/工单查询",description = "获取地区")
    @GetMapping("/getAllByPId")
    @ApiOperation(value = "获取地区", produces = "application/json")
    public Resp<LinkedHashSet<OrderDeliveryMenu>> getAllByPId() {
        List<OrderDeliveryMenu> set = workOrderService.getAllByPId();
        return Resp.success(set);
    }



    //  @LogAnnotation(module = "工单派送/工单查询",description = "根据pId获取单位/配电房")
    @PostMapping("/getAllByPIds")
    @ApiOperation(value = "根据pId获取单位/配电房", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "pId", value = "pid", dataType = "Integer"),
    })
    public Resp<LinkedHashSet<OrderDeliveryMenu>> getAllByPIds(String pId) {
        if(pId == null){
            Resp.fail("区域或者单位没有选择");
        }
        List<OrderDeliveryMenu> list = workOrderService.getAllByPIds(pId);
        return Resp.success(list);
    }


    // @LogAnnotation(module = "工单派送/工单查询",description = "根据配电房Id获取设备")
    @PostMapping("/getDeviceByRoomId")
    @ApiOperation(value = "根据配电房Id获取设备", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "roomId", value = "roomId", dataType = "Integer"),
    })
    public Resp<LinkedHashSet<OrderDeliveryMenu>> getDeviceByRoomId(String roomId) {
        if(roomId == null){
            Resp.fail("区域或者单位没有选择");
        }
        List<Device> list = deviceService.selectByRoomId(roomId);
        return Resp.success(list);
    }


    // @LogAnnotation(module = "工单派送/工单查询",description = "根据配电房Id获取运维人员")
    @PostMapping("/getMaintainer")
    @ApiOperation(value = "根据配电房Id获取运维人员", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "powerroomId", value = "配电房id", dataType = "Integer"),
    })
    public Resp<List<Maintainer>> getMaintainer(String powerroomId) {
        if(powerroomId == null){
            Resp.fail("没有运维人员");
        }
        List<Maintainer> list = workOrderService.getMaintainer(powerroomId);
        return Resp.success(list);
    }


    @LogAnnotation(module = "工单派送/工单查询",description = "根据运维人员Id分配工单")
    @PostMapping("/insertMaintainer")
    @ApiOperation(value = "根据运维人员Id分配工单", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "maintainerId", value = "运维人员id", dataType = "String",defaultValue="16195999"),
            @ApiImplicitParam(paramType = "query", name = "orderDeliveryId", value = "工单id", dataType = "String",defaultValue = "61618410" ),
            @ApiImplicitParam(paramType = "query", name = "projectName", value = "项目名", dataType = "String",defaultValue = "新华书店项目"),
            @ApiImplicitParam(paramType = "query", name = "roomName", value = "配电房名", dataType = "String" ,defaultValue = "物流中心配电房"),
            @ApiImplicitParam(paramType = "query", name = "deviceName", value = "设备名", dataType = "String",defaultValue = "4BL1-4#变压器电源进线柜"),
            @ApiImplicitParam(paramType = "query", name = "phone", value = "手机号", dataType = "String",defaultValue = "13253637565"),
    })
    public Resp insertMaintainer(String maintainerId,String orderDeliveryId,String projectName,String roomName,String deviceName,String phone) throws MalformedURLException, UnsupportedEncodingException {
        int i = workOrderService.updateMaintainer(maintainerId, orderDeliveryId,projectName,roomName,deviceName,phone);
        if (i == 1){
            return Resp.success("添加成功");
        }else{
            return Resp.fail("添加失败");
        }
    }



    // @LogAnnotation(module = "工单派送/工单查询",description = "获取最新的告警信息")
    @PostMapping("/getNewOrderDelivery")
    @ApiOperation(value = "获取最新的告警信息", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "token", value = "token", dataType = "String",defaultValue = "70N9D9nrpn"),
    })
    public Resp getNewOrderDelivery(String token) {
        OrderDelivery orderDelivery = orderDeliveryService.getOrderDelivery(token);
        return Resp.success(orderDelivery);
    }


    @PostMapping("/getNotOrderDelivery")
    @ApiOperation(value = "获取未解决的告警信息", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "token", value = "token", dataType = "String",defaultValue = "70N9D9nrpn"),
    })
    public Resp getOrderDelivery(String token) {
        OrderDelivery orderDelivery = orderDeliveryService.getNewOrderDelivery(token);
        if (orderDelivery != null){
            return Resp.success(true);
        }else {
            return Resp.success(false);
        }
    }


    @PostMapping("/getWorkOrder")
    @ApiOperation(value = "根据项目Id查询已完成的工单", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "projectId", value = "projectId", dataType = "String",defaultValue = ""),
    })
    public Resp getWorkOrder(String projectId) {
        List<WorkOrder> workOrderList = workOrderService.getWorkOrderByProjectId(projectId);
        return Resp.success(workOrderList);
    }


    @PostMapping("/getWorkOrderById")
    @ApiOperation(value = "根据派单号Id查询单个记录", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "orderDeliveryId", value = "orderDeliveryId", dataType = "String",defaultValue = ""),
    })
    public Resp getWorkOrderById(String orderDeliveryId) {
        WorkOrder workOrder = workOrderService.getWorkOrderByOrderDeliveryId(orderDeliveryId);
        return Resp.success(workOrder);
    }


}
